package org.example.votingsystem.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        System.out.println("跨域");
//        允许携带cookie时不可以设置为* 否则前端报错
        httpServletResponse.setHeader("Access-Control-Allow-Origin",httpServletRequest.getHeader("origin"));//允许所有请求跨域
        httpServletResponse.setHeader("Access-Control-Allow-Methods","*");//允许跨域的请求方法Get Post HEAD等
        httpServletResponse.setHeader("Access-Control-Allow-Headers","*");//允许跨域的请求头
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");//是否携带cookie

        chain.doFilter(httpServletRequest,httpServletResponse);

    }
}
